package world.zwq.gulimall.product.web;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import world.zwq.gulimall.product.entity.CategoryEntity;
import world.zwq.gulimall.product.service.CategoryService;
import world.zwq.gulimall.product.vo.Catalog2Vo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangwq
 * @date 2021/7/31 23:04
 */
@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redisson;

    @GetMapping({"/","index.html"})
    public String index(Model model){
        //TODO 1、查出所有的1级数据
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }

    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2Vo>> getCatalogJson(){

        Map<String, List<Catalog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    @GetMapping("/hello")
    @ResponseBody
    private String hello(){
        //获取一把锁，只有锁名字一样，就是同一个
        RLock lock = redisson.getLock("hello-lock");
        lock.lock();
        try {
            System.out.println("加锁成功，执行业务---" + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //解锁，假设代码没有运行，redisson会不会死锁
            lock.unlock();
            System.out.println("释放锁" + Thread.currentThread().getId());
        }

        return "hello";
    }
}
